/**
 * @Author: yuanmanxue
 * @Date:   2017-09-27 03:26:29
 * @Last modified by:   yuanmanxue
 * @Last modified time: 2018-01-11 04:22:26
 */

/*
Iterator 和 for...of循环
1.什么是Iterator接口
2.Iterator的基本用法
3.for...of原理和Iterator接口之间的关系
*/

{
  let arr=['hello','world'];
  let map=arr[Symbol.iterator]();
  console.log(map.next());//{value: "hello", done: false}
  console.log(map.next());//{value: "world", done: false}
  console.log(map.next());//{value: undefined, done: true}
}

{
  //自定义iterator接口   object并没有帮我们内置iterator接口
  //先遍历start 在遍历end
  let obj={
    start:[1,2,3],
    end:[5,6,9],
    //遍历对象里面的的key/value
    [Symbol.iterator](){
      let self=this;
      let index = 0;
      let arr=self.start.concat(self.end);
      let len=arr.length;
      return {
        next(){
          if(index<len){
            return {
              value:arr[index++],
              done:false
            }
          }else{
            return {
              value:arr[index++],
              done:true
            }
          }
        }
      }
    }
  }
  for(let key of obj){
    console.log(key);
  }
}

{
    let arr=['hello','world'];
    for(let value of arr){
      console.log(value);//hello  world
    }
}

{
  let arr=[1,[2,[3,[4,5],6],7],8];
  Array.prototype[Symbol.iterator]=function(){
    let arr=[].concat(this),
        index=0;
    let getFirst=function(array){
        let first=array[0];
        if(first instanceof Array){
          return getFirst(array[0]);
        }else if(first!==undefined){
          return array.shift()
        }else{
          return ''
        }
    }
    return {
      next:function(){
        let item=getFirst(arr);
            if(item){
              return {
                value:item,
                done:false
              }
            }else{
              return {
                    done:true
              }
            }
        }
      }
  }
  for(let value of arr){
     console.log(value);
  }
}
//类数组的遍历
{
  let obj = {
    length:2,
    '0':'asd',
    '1':'ddd'
  }
  obj[Symbol.iterator]=[][Symbol.iterator]
  for(let i of obj){
    console.log(i);
  }
}
